package com.ruoyi.auth.service;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.RemoteServerService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author: Wuzh
 * @Description:
 * @Date Created in 22:08 2025-03-12
 * @return
 */
@Component
public class FusionLoginService {

    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private RemoteServerService remoteServerService;

    /**
     * APP融合登录，首先查询该手机有无注册
     * 1）没有注册，则先注册
     * 2）已经注册，直接登录
     * @param mobile
     * @return
     */
    @Transactional (rollbackFor = Exception.class)
    public LoginUser fusionLogin (String mobile, String bundleId) {
        if ( StringUtils.isBlank ( mobile ) ) {
            throw new RuntimeException ( "手机号为空，解析失败！" );
        }
        R<LoginUser> loginUserR = remoteUserService.getUserByMobile ( mobile, SecurityConstants.INNER );
        LoginUser user = loginUserR.getData ();
        if ( user == null ) {
            //手机号第一次登录时，随机生成username，以及系统随机给一张icon；并且设定这个用户目前从属于哪个APP ??
            SysUser sysUser = new SysUser ();
            sysUser.setPhonenumber ( mobile );
            sysUser.setNickName ( mobile.substring ( mobile.length () - 4 ).concat ( "_用户" ) );
            sysUser.setUserName ( mobile );
            R<SysUser> sysUserR = remoteUserService.saveUserInfo ( sysUser, SecurityConstants.INNER );
            //2.存APP和用户的关联关系
            AjaxResult app = remoteServerService.getAppByPackage(bundleId);


//            UserRelationEntity relationDO = new UserRelationEntity ();
//            relationDO.setBizId ( app.getData ().getId () );//APP ID
//            relationDO.setType ( 2 );
//            relationDO.setUserId ( sysUserR.getData ().getUserId () );
//            remoteServerService.insert ( relationDO );

            user = new LoginUser ();
            user.setUserid ( sysUserR.getData ().getUserId () );
            user.setUsername ( sysUserR.getData ().getUserName () );
            user.setNickName ( sysUserR.getData ().getNickName () );
        } else {
            // 校验是否禁用
//            if ( CommonStatusEnum.isDisable ( adminUserDO.getStatus () ) ) {
//                createLoginLog ( adminUserDO.getId (), adminUserDO.getUsername (), LoginLogTypeEnum.LOGIN_FUSION, LoginResultEnum.USER_DISABLED );
//                throw exception ( AUTH_LOGIN_USER_DISABLED );
//            }
            //设置token和时间
        }
        return user;
    }

}
